package coderead.plugin.ui.quickFix;
/**
 * @Copyright 源码阅读网 http://coderead.cn
 */

import coderead.plugin.MavenSearchAction;
import coderead.plugin.PluginIcons;
import com.intellij.codeInsight.intention.LowPriorityAction;
import com.intellij.codeInsight.intention.impl.BaseIntentionAction;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.IconLoader;
import com.intellij.openapi.util.Iconable;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiJavaCodeReferenceElement;
import com.intellij.psi.SmartPointerManager;
import com.intellij.psi.SmartPsiElementPointer;
import com.intellij.util.IconUtil;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.util.regex.Pattern;

/**
 * @author 鲁班大叔
 * @date 2021
 */
public class CassSearchQuickFixAction extends BaseIntentionAction implements LowPriorityAction, Iconable {
    private final SmartPsiElementPointer<PsiJavaCodeReferenceElement> myRef;
    private final Pattern compile;

    public CassSearchQuickFixAction(PsiJavaCodeReferenceElement refElement) {
        myRef = SmartPointerManager.getInstance(refElement.getProject()).createSmartPsiElementPointer(refElement);

         compile = Pattern.compile("(\\p{javaJavaIdentifierStart}\\p{javaJavaIdentifierPart}*\\.)*\\p{Lu}\\p{javaJavaIdentifierPart}+");

    }

    @Nls(capitalization = Nls.Capitalization.Sentence)
    @Override
    public String getFamilyName() {
        return "Search Class ";
    }

    @Nullable
    private PsiJavaCodeReferenceElement getElement() {
        PsiJavaCodeReferenceElement rootElement = myRef.getElement();
        if (rootElement==null) {
            return null;
        }
        while (rootElement.getParent() != null &&
                rootElement.getParent() instanceof PsiJavaCodeReferenceElement) {
            rootElement= (PsiJavaCodeReferenceElement) rootElement.getParent();
        }

        return rootElement;
    }

    @Override
    public boolean isAvailable(Project project, Editor editor, PsiFile file) {
        PsiJavaCodeReferenceElement element = getElement();
        if (element == null) {
            return false;
        }
//        element.ge
        if (!compile.matcher(element.getText()).matches()) {
            return false;
        }
        setText(String.format("Search Class for '%s'", element.getText()));
        return true;
    }

    @Override
    public void invoke( Project project, Editor editor, PsiFile file)
            throws IncorrectOperationException {
        PsiJavaCodeReferenceElement element = getElement();
        MavenSearchAction.openClassSearch(element.getText(), project);
    }

    @Override
    public Icon getIcon(int flags) {
        return IconUtil.scale(PluginIcons.MavenSearch_128PNG,null,
                0.125f);
    }

}
